package com.xing.oauth.controller;

import com.alibaba.fastjson.JSON;
import com.xing.oauth.common.response.ResultCode;
import com.xing.oauth.server.aligenieController.vo.OAuthResponseVo;
import com.xing.oauth.server.model.TokenDto;
import com.xing.oauth.server.service.AligenieTokenService;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

@Controller
@RequestMapping("/aligenie")
public class AligenieAccessTokenController extends BaseController {


    /**
     * 下发长短token与刷新token
     *
     * @param request
     * @return
     */
    @RequestMapping("/token")
    public ResponseEntity token(HttpServletRequest request) {

        try {
            //构建OAuth请求
            OAuthTokenRequest oAuthRequest = new OAuthTokenRequest(request);

            LOGGER.info("获取token：接口入参为：{}", JSON.toJSONString(oAuthRequest));

            //检验提交的客户端id和secret是否正确
            if (!oAuthService1.checkClientIdAndClientSecret(oAuthRequest.getClientId()
                    , oAuthRequest.getClientSecret(), properties.getClientName())) {
                LOGGER.info("客户端id和secrect错误，clientId:{},secret:{}", oAuthRequest.getClientId(), oAuthRequest.getClientSecret());
                return OAuthResponseVo.getErrorResponse(ResultCode.UNAUTHORIZED);
            }
            //这样写是把下发长短token与刷新token两个功能通过一个接口来实现的
            //做一个开关，根据grant_type：是否是refresh_token来做校验
            String grantType = "refresh_token";
            TokenDto tokenDto = null;

            if (grantType.equals(oAuthRequest.getGrantType())) {
                //刷新token
                tokenDto = aligenieTokenService.refreshToken(oAuthRequest);
                if (tokenDto == null) {
                    //返回授权凭证RT已过期或失效
                    return OAuthResponseVo.getErrorResponse(ResultCode.EXPIRED_REFRESHTOKEN_CREDENTIAL);
                } else {
                    return OAuthResponseVo.getTokenResponse(tokenDto);
                }
            } else {
                tokenDto = aligenieTokenService.accessToken(oAuthRequest);
                if (tokenDto == null) {
                    return OAuthResponseVo.getErrorResponse(ResultCode.EXPIRED_REFRESHTOKEN_CREDENTIAL);
                } else {
                    return OAuthResponseVo.getTokenResponse(tokenDto);
                }
            }
        } catch (Exception e) {
            LOGGER.info("下发token或者获取token异常：{}",e.getMessage());
            //构建错误响应
            return OAuthResponseVo.getErrorResponse(ResultCode.INTERNAL_ERROR);
        }

    }
}
